package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.StrategyComment;
import cn.wolfcode.luowowo.comment.service.IStrategyCommentService;
import cn.wolfcode.luowowo.comment.query.StrategyCommentQuery;
import cn.wolfcode.luowowo.comment.repository.StrategyCommentRepository;
import cn.wolfcode.luowowo.common.exception.LogicException;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * 攻略评论服务
 */
@Service
public class StrategyCommentServiceImpl implements IStrategyCommentService{

    @Autowired
    private StrategyCommentRepository strategyCommentRepository; //操作简单的crud

    @Autowired
    private MongoTemplate mongoTemplate; //操作高级查询


    @Override
    public void save(StrategyComment comment) {
        comment.setCreateTime(new Date());

        strategyCommentRepository.save(comment);
    }

    //分页查询
    @Override
    public Page query(StrategyCommentQuery qo) {

        Query query = new Query();

        //条件
        if(qo.getDetailId() != -1){
            query.addCriteria(Criteria.where("detailId").is(qo.getDetailId()));
        }

        //分页条件
        PageRequest pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.DESC, "createTime");

        //查总数
        //toatl
        long total = mongoTemplate.count(query, StrategyComment.class);

        //设置分页条件
        query.with(pageable);

        //查当前页显示数据集合
        List<StrategyComment> list = mongoTemplate.find(query, StrategyComment.class);

        //分页封装对象
        return new PageImpl(list,pageable,total);
    }

    //攻略评论点赞
    @Override
    public void commentThumbUp(String commentId, Long userId) {
        //1.判断当前请求时点赞还是取消点赞操作

        Optional<StrategyComment> op = strategyCommentRepository.findById(commentId);
        StrategyComment comment = op.get(); //根据id拿到评论对象

        if(comment == null){
            throw new LogicException("参数异常");
        }

        List<Long> list = comment.getThumbuplist();

        //1.1 判断当前用户说在点赞集合中
        //1.2 如果在表示当前是取消点赞,否则点赞
        if(list.contains(userId)){
            //3.如果是取消点赞操作,点赞数-1,将当前用户id移除点赞集合
            comment.setThumbupnum(comment.getThumbupnum() -1);
            list.remove(userId);
        }else{
            //2.如果是点赞操作,点赞数+1,将当前用户id添加到点赞集合中
            comment.setThumbupnum(comment.getThumbupnum() +1);
            list.add(userId);
        }

        //重新放回数据库中
        strategyCommentRepository.save(comment);
    }
}
